import tkinter as tk
from utils import create_centered_window
from recorder import Recorder
from workflow_selector import WorkflowSelector

# 工作流目录
WORKFLOWS_DIR = "workflows"


class MainApplication:
    def __init__(self):
        self.root = create_centered_window(title="自动化执行系统", width=400, height=420)

        # 当窗口关闭时退出整个程序
        self.root.protocol("WM_DELETE_WINDOW", self.quit_application)

        self.create_ui()

    def create_ui(self):
        # 主框架
        main_frame = tk.Frame(self.root, padx=30, pady=30, bg='#f0f0f0')
        main_frame.pack(expand=True, fill=tk.BOTH)

        # 标题
        title_label = tk.Label(
            main_frame,
            text="自动化执行系统",
            font=("微软雅黑", 16, "bold"),
            bg='#f0f0f0',
            fg='#333333'
        )
        title_label.pack(pady=(0, 10))

        # 功能按钮框架
        button_frame = tk.Frame(main_frame, bg='#f0f0f0')
        button_frame.pack(expand=True, fill=tk.BOTH)

        # 统一按钮样式
        button_style = {
            'font': ("微软雅黑", 11),
            'width': 20,  # 固定按钮宽度
            'height': 2,  # 固定按钮高度
            'relief': tk.RAISED,
            'cursor': 'hand2',
        }

        # 录制模式按钮
        record_button = tk.Button(
            button_frame,
            text="录制模式",
            command=self.open_recorder,
            **button_style
        )
        # 使用pack并设置合适的间距
        record_button.pack(pady=10)

        # 手动执行按钮
        manual_button = tk.Button(
            button_frame,
            text="手动执行模式",
            command=lambda: self.select_workflow(False),
            **button_style
        )
        manual_button.pack(pady=10)

        # 自动执行按钮
        auto_button = tk.Button(
            button_frame,
            text="自动执行模式",
            command=lambda: self.select_workflow(True),
            **button_style
        )
        auto_button.pack(pady=10)

        # 退出按钮
        exit_button = tk.Button(
            main_frame,
            text="退出",
            command=self.quit_application,
            font=("微软雅黑", 10),
            width=10,  # 固定宽度
            relief=tk.RAISED,
            cursor='hand2',
            bg='#ff6666',  # 红色背景
            fg='white'  # 白色文字
        )
        # 给退出按钮居中显示，并确保有足够的间距
        exit_button.pack(side=tk.BOTTOM)

    def quit_application(self):
        """退出应用程序"""
        self.root.quit()
        self.root.destroy()

    def select_workflow(self, auto_mode):
        """选择工作流"""
        # 隐藏主窗口
        self.root.withdraw()
        # 显示工作流选择窗口
        WorkflowSelector(self.root, WORKFLOWS_DIR, auto_mode)

    def open_recorder(self):
        """打开录制模式"""
        # 隐藏主窗口
        self.root.withdraw()
        # 显示录制窗口
        Recorder(self.root, WORKFLOWS_DIR)

    def run(self):
        self.root.mainloop()


if __name__ == "__main__":
    app = MainApplication()
    app.run()
